package com.music.model;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;

import javax.swing.JFileChooser;

import com.thoughtworks.xstream.XStream;

public class Serialization implements Data {

	final static XStream xstream = new XStream(); // objet permettant la serialisation

	static String fileChooser(String opt){
		JFileChooser save = new JFileChooser();
		if (opt == "write")
			save.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
		if (save.showSaveDialog(null) == JFileChooser.APPROVE_OPTION)
//			Data.dirMusic = save.getSelectedFile().getPath();
			return save.getSelectedFile().getPath();
		return Data.dirMusic;
	}

	// //////////////////////////////////////////////////////////////////////////////////////
	// ////// SERIALIZATION ////////
	// //////////////////////////////////////////////////////////////////////////////////////

	/**
	 * @param obj
	 *            : an object that we want to serialize into a XML file
	 */
	static void writeXML(ArrayList<Track> track) {
		BufferedWriter writer = null;
		try {
			writer = new BufferedWriter(new FileWriter(Data.dirLib, false));
		} catch (IOException e) {
			System.err.println("Problème d'écriture sur le fichier : "
					+ Data.dirLib);
		}
		Serialization.xstream.toXML(track, writer);
	}

	/**
	 * @return a list of tracks contained in the xml file
	 */
	@SuppressWarnings("unchecked")
	static ArrayList<Track> readXML() {
		BufferedReader reader = null;
		try {
			reader = new BufferedReader(new FileReader(Data.dirLib));
		} catch (FileNotFoundException e) {
			System.err.println("Impossible de charger le fichier : "
					+ Data.dirLib);
		}
		return (ArrayList<Track>) Serialization.xstream.fromXML(reader);
	}
}
